//
//  JKMeViewController.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/13.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit
import JKAlertX

class JKMeViewController: JKBaseViewController {

    public var isSettingIn = false
    
    public var logoutBlock: (() -> Void)?
    
    @IBOutlet weak var IconButton: UIButton!
    @IBOutlet weak var logoutButton: UIButton!
    @IBOutlet weak var changeNameButton: UIButton!
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var nameLabel: UILabel!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navTitle = "个人主页"
        
        nameLabel.text = JKAccountManager.shared.userName
        
        self.logoutButton.layer.borderColor = UIColor.black.withAlphaComponent(0.3).cgColor
        self.logoutButton.layer.borderWidth = 1
        
        self.textView.delegate = self
        
        let imgPath = ((NSHomeDirectory() as NSString).appendingPathComponent("Documents") as NSString).appendingPathComponent("userIcon.png")
        
        var img = UIImage(contentsOfFile: imgPath)
        
        if (img == nil) {
            
            img = UIImage(named: "myIcon")?.jk_circleImage()
        }
        
        self.IconButton.setImage(img?.jk_circleImage(borderWidth: 5, borderColor: JKColor(57, 150, 118)), for: UIControlState.normal)
        self.IconButton.setImage(img?.jk_circleImage(borderWidth: 5, borderColor: JKMainColor), for: UIControlState.highlighted)
    }
    
    // MARK: - 点击事件
    
    override func navBackButtonClick() {
        
        if isSettingIn {
            
            navigationController?.popViewController(animated: true)
            
            return
        }
        
        let mainNav = navigationController as! JKMainNavigationController
        
        if mainNav.showLeftVcBlock != nil {
            
            mainNav.showLeftVcBlock!()
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        if !changeNameButton.isHidden { return }
        
        saveName()
    }
    
    /** saveName */
    private func saveName() {
        
        JKHideKeyBoard()
        
        if !self.textView.hasText || self.textView.text.count > 7 {
            
            let _ = JKAlertView(title: "提示", message: "请输入正确的昵称~\n最多7个字符哦~", style: JKAlertStylePlain).addAction(JKAlertAction(title: "知道了", style: JKAlertActionStyleDefault, handler: nil))?.show()?.setDismissComplete()({
                
                self.textView.becomeFirstResponder()
            })
            
            return
        }
        
        self.changeNameButton.isHidden = false
        self.nameLabel.text = self.textView.text
        
        UserDefaults.standard.set(textView.text, forKey: JKUserNameKey)
        UserDefaults.standard.synchronize()
        
        self.textView.text = nil
        self.textView.isHidden = true
    }
    
    @IBAction func IconButtonClick(_ sender: Any) {
        
        let _ = JKAlertView(title: nil, message: "修改头像", style: JKAlertStyleActionSheet).addAction(JKAlertAction(title: "拍照", style: JKAlertActionStyleDefault, handler: { (action) in
            
            self.updateIconWithSourType(type: UIImagePickerControllerSourceType.camera)
            
        }))?.addAction(JKAlertAction(title: "从相册选择", style: JKAlertActionStyleDefault, handler: { (action) in
            
            self.updateIconWithSourType(type: UIImagePickerControllerSourceType.photoLibrary)
            
        }))?.show()
    }
    
    @IBAction func changeNameButtonClick(_ sender: UIButton) {
        
        sender.isHidden = true
        
        self.textView.isHidden = !sender.isHidden
        self.textView.text = self.nameLabel.text
        self.textView.becomeFirstResponder()
    }
    
    @IBAction func logoutButtonCilck(_ sender: Any) {
        
        JKAccountManager.logout()
        
        if isSettingIn {
            
            navigationController?.popViewController(animated: true)
            
            return
        }
        
        if logoutBlock != nil {
            
            logoutBlock!()
        }
    }
    
    private func updateIconWithSourType(type: UIImagePickerControllerSourceType) {
        
        if !UIImagePickerController.isSourceTypeAvailable(type) { return }
        
        let imagePicker = UIImagePickerController();
        imagePicker.sourceType = type;
        imagePicker.allowsEditing = true;
        
        imagePicker.delegate = self;
        present(imagePicker, animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JKMeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image = info[UIImagePickerControllerEditedImage] as! UIImage
        
        let newImg = image.jk_circleImage()
        
        let newImgData = UIImagePNGRepresentation(newImg);
        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
        let filePath = (path as NSString).appendingPathComponent("userIcon.png")
        
        try? newImgData!.write(to: URL(fileURLWithPath: filePath))
        
//        [newImgData writeToFile:filePath atomically:YES];

        let newImgNormal = newImg.jk_circleImage(borderWidth: 5, borderColor: JKColor(57, 150, 118))
        let newImgHighlighted = newImg.jk_circleImage(borderWidth: 5, borderColor: JKMainColor)
        
        IconButton.setImage(newImgNormal, for: UIControlState.normal)
        IconButton.setImage(newImgHighlighted, for: UIControlState.highlighted)
        
        dismiss(animated: true, completion: nil)
    }
}

extension JKMeViewController: UITextViewDelegate {
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        if text == "\n" {
            
            saveName()
            
            return false
        }
        
        return true
    }
}

extension JKMeViewController {
    
    override func updateSkin() {
        
        super.updateSkin()
        
        if self.vcSkinModel == JKNightSkinModelValue { // 夜间模式
            
            self.nameLabel.textColor = JKColor(186, 186, 186);
            
            self.logoutButton.setBackgroundImage(UIImage(named: "logout_night_normal"), for: UIControlState.normal)
            self.logoutButton.setBackgroundImage(UIImage(named: "logout_night_highlighted"), for: UIControlState.highlighted)
            
        }else{ // 日间模式
            
            self.nameLabel.textColor = UIColor.black
            
            self.logoutButton.setBackgroundImage(UIImage(named: "logout_day_normal"), for: UIControlState.normal)
            self.logoutButton.setBackgroundImage(UIImage(named: "logout_day_highlighted"), for: UIControlState.highlighted)
        }
        
    }
}
